<?php

namespace app\admin\controller;
use app\common\controller\Backend;
use app\admin\model\Admin;
use app\common\model\Category as CategoryModel;
use fast\Tree;
use think\Db;
use app\common\model\Category;
use app\common\model\Materials;
use app\common\model\UserGroup;
use app\common\model\Attachment;
/**
 * 微信用户管理
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Message extends Backend
{
	protected $noNeedLogin = [''];
    protected $noNeedRight = [''];

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->model = model('app\common\model\Messages');
    }
    public function index(){
    	if ($this->request->isAjax()) {
    		$map=[];
    		$map['wechat_id'] = $this->wechat_id;
    		list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    		$list = $this->model->with('group')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
			$result = array("total" => $list->total(), "rows" => $list->items());
			return json($result);
    	}
    	return $this->view->fetch();
    }
    public function add(){
        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            $mess = [];
            if($data['group'] > 0){
                $mess['filter'] = ['is_to_all'=>False,'group_id'=>$data['group']];
            }
            // 文字回复
            if($data['type'] == 'text'){
                if(empty($data['content'])){
                    $this->error('请输入回复内容');
                }
                $mess['text'] = ['content'=>$data['content']];
            }
            // 图片回复
            if($data['type'] == 'image'){
                if(empty($data['image'])){
                    $this->error('请上传回复图片');
                }
                $mess['images'] = ['media_ids'=>[$data['media_id']]];
            }
            
            // 图文
            if($data['type'] == 'mpnews'){
                if(empty($data['material_id'])){
                    $this->error('请选择图文信息');
                }
                $media_id = Materials::where('id',$data['material_id'])->value('media_id');
                if(empty($media_id)){
                    $this->error('图文媒体ID不存在，请重新选择');
                }
                $mess['mpnews'] = ['media_id'=>$media_id];
            }
            $mess['msgtype'] = $data['type'];
            
            $data['create_at'] = time();
            $data['wechat_id'] = $this->wechat_id;
            Db::startTrans();
            try{
                $id = 1;//$this->model->insert($data,false,true);
                $result = true;//$this->weobj()->sendGroupMassMessage($mess);
                if(!$result || (isset($result['errcode']) && $result['errcode'] == -1)){
                    Db::rollback();
                    $this->error($result['errmsg']);
                }
            }catch (\think\Exception $e){
                Db::rollback();
                $this->error('消息发送失败');
            }
            Db::commit();
            //$this->model->where('id',$id)->update(['msg_id'=>$result['msg_id']]);
            $wechats = $this->request->post('wechat/a');
            if(is_array($wechats) && !empty($wechats)){
                foreach($wechats as $wechat_id){
                    \fast\Async::hook('message',['wechat_id'=>$this->wechat_id,'data'=>$data,'wechatId'=>$wechat_id]);
                }
            }
            $this->success('消息发送成功');

        }
        $groups = UserGroup::where(['wechat_id'=>$this->wechat_id])->select();
        $this->assign('groups',$groups);
        return $this->view->fetch();
    }
    public function detail($ids=null){
       $row = $this->model->where(['wechat_id'=>$this->wechat_id,'id'=>$ids])->find();
        if(empty($row)){
            $this->error('数据不存在');
        }
        $t['text'] = $t['image'] = $t['mpnews'] = "none";
        if($row['type'] == 'text'){
            $t['text'] = "block";
        }
        if($row['type'] == 'image'){
            $t['image'] = "block";
        }
        if($row['type'] == 'mpnews'){
            $t['mpnews'] = "block";
            if((int)$row['material_id'] > 0){
                $material = Materials::get($row['material_id']);
                if(!empty($material)){
                    $material['items'] = (new Materials)->getMaterialItems($material->id);
                }
                $this->assign('material',$material);
            }
        }
        $groups = UserGroup::where(['wechat_id'=>$this->wechat_id])->select();
        $this->assign('groups',$groups);
        $this->assign('t',$t);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    
}